// 封装选择框（参数：选择框选项， 选项点击的回调函数）
function YearSelect(options, optionFunction) {
  const selectWrapper = document.createElement('div');
  let optionsHTML = []
  options.forEach(option => {
    let element = document.createElement('div')
    element.innerText = option
    element.className = "select-option"
    element.onclick = (event) => {
      optionFunction(event, element, selectWrapper)
    }
    optionsHTML.push(element)
  });
  let select = document.createElement('div')
  select.className = "select"
  let selectOptions = document.createElement('div')
  selectOptions.className = "select-options"
  optionsHTML.forEach(item => {
    selectOptions.appendChild(item)
  })
  select.appendChild(selectOptions)
  selectWrapper.appendChild(select)
  return selectWrapper
}
//添加选择框（写选项被点击的回调）
function addSelect(selectDataArray) {
  let select = YearSelect(selectDataArray, (event, element, selectWrapper) => {
    let selectOption = document.getElementsByClassName("select-option")
    for (let i = 0; i < selectOption.length; i++) {
      selectOption[i].style = "font-weight: normal"
    }
    element.style = "font-weight: 600;"
    signUpYearInput.value = element.innerText
    selectWrapper.style.display = "none"
    signUpYearInput.className = "sign-up-input"
    event.stopPropagation()
  })
  signUpYear.appendChild(select)
  return select
}

//课程安排内容创建
function createcourseContentHTML(courseArrangementData, tab) {
  let tempCourseArrangementData = null
  if (tab == "全部") {
    tempCourseArrangementData = courseArrangementData
  } else {
    tempCourseArrangementData = courseArrangementData.filter(item => item.tags.indexOf(tab) != -1)
  }
  let courseContentHTML = ``
  tempCourseArrangementData.forEach(item => {
    let tagsHTML = ``
    item.tags.forEach(tag => {
      tagsHTML += `<div class="tag tag-${tag}">${tag}</div>`
    })
    courseContentHTML += `
    <!-- 课程安排内容项 -->
    <div class="course-item">
      <!-- 课程安排内容项左边 -->
      <div class="course-item-left">
        <!-- 课程安排内容项左边图片 -->
        <img class="course-item-img" src="${item.image}" />
      </div>
      <!-- 课程安排内容项右边 -->
      <div class="course-item-right">
        <!-- 课程安排内容项右边标题 -->
        <div class="course-item-title">
          ${item.title}
        </div>
        <!-- 课程安排内容项右边内容 -->
        <div class="course-item-content">
          ${item.content}
        </div>
        <!-- 课程安排内容项的标签栏 -->
        <div class="tags">
          ${tagsHTML}
        </div>
      </div>
    </div>
  `
  })

  return courseContentHTML;
}
// 重置tab
function resetTabs(tabs) {
  for (let i = 0; i < tabs.length; i++) {
    tabs[i].className = "tab"
  }
}

// 封装地区级联选择框（参数： 级联选择内容， 复选项被点击的回调， 子选项被点击的回调）
function AreaCascader(options, parentOptionFunction, childOptionFunction) {
  let cascaderWrapper = document.createElement("div")
  let cascader = document.createElement("div")
  cascader.className = "cascader"

  let cascaderOptions = document.createElement("div")
  cascaderOptions.className = "cascader-options"
  let cascaderParentOptions = document.createElement("div")
  cascaderParentOptions.className = "cascader-parent-options"
  let cascaderChilrenOptions = document.createElement('div')
  cascaderChilrenOptions.className = "cascader-chilren-cptions"
  for (let i = 0; i < options.length; i++) {
    let cascaderChildOptions = document.createElement("div")
    cascaderChildOptions.className = "cascader-child-options"
    for (let j = 0; j < options[i].child.length; j++) {
      let cascaderChildOption = document.createElement("div")
      cascaderChildOption.className = "cascader-child-option"
      cascaderChildOption.innerText = options[i].child[j]
      cascaderChildOption.onclick = (event) => {
        childOptionFunction(event, cascaderChildOptions, cascaderChildOption, cascaderWrapper)
      }
      cascaderChildOptions.appendChild(cascaderChildOption)
    }
    if (i != 0) {
      cascaderChildOptions.style.display = "none"
    }
    let cascaderParentOption = document.createElement("div")
    cascaderParentOption.className = "cascader-parent-option"
    cascaderParentOption.innerText = options[i].text
    if (i == 0) {
      cascaderParentOption.style.fontWeight = "600"
    }
    cascaderParentOption.onclick = (event) => {
      parentOptionFunction(event, cascaderParentOption, cascaderChildOptions)
    }
    cascaderParentOptions.appendChild(cascaderParentOption)

    cascaderChilrenOptions.appendChild(cascaderChildOptions)
  }
  cascaderOptions.appendChild(cascaderParentOptions)
  cascaderOptions.appendChild(cascaderChilrenOptions)
  cascader.appendChild(cascaderOptions)
  cascaderWrapper.appendChild(cascader)
  return cascaderWrapper
}

// 增加级联选择（参数： 级联选择数据）并完成回调方法
function addCascader(cascaderDataArray) {
  let cascader = null
  cascader = AreaCascader(cascaderDataArray, (event, element, childElement) => {
    let cascaderParentOptions = document.querySelectorAll(".cascader-parent-option")
    let cascaderChildOptions = document.querySelectorAll(".cascader-child-options")
    for (let i = 0; i < cascaderParentOptions.length; i++) {
      cascaderParentOptions[i].style.fontWeight = "normal"
      cascaderChildOptions[i].style.display = "none"
    }
    let childElementOptions = childElement.childNodes
    for (let i = 0; i < childElementOptions.length; i++) {
      childElementOptions[i].style.fontWeight = "normal"
      if (childElementOptions[i].innerText == signUpAreaInput.value) {
        childElementOptions[i].style.fontWeight = "600"
      }
    }
    element.style.fontWeight = "600"
    childElement.style.display = "grid"
    event.stopPropagation()
  }, (event, parentElemnt, element, cascaderWrapper) => {

    let cascaderChildOptions = parentElemnt.childNodes
    for (let i = 0; i < cascaderChildOptions.length; i++) {
      cascaderChildOptions[i].style.fontWeight = "normal"
    }
    element.style.fontWeight = "600"
    signUpAreaInput.value = element.innerText
    cascaderWrapper.style.display = "none"
    signUpAreaInput.className = "sign-up-input"
    event.stopPropagation()
  })
  signUpArea.appendChild(cascader)
  return cascader
}


// 封装提示框（参数：成功或失败，文本）
function createTipDialog(isSuccess, text) {
  let tipDiv = document.createElement('div')
  if (isSuccess) {
    tipDiv.className = "tip success-tip"
  } else {
    tipDiv.className = "tip danger-tip"
  }
  let tipText = document.createElement("div")
  tipText.className = "tip-text"
  tipText.innerText = text
  tipDiv.appendChild(tipText)
  return tipDiv
}



window.onload = () => {

  // 地区级联选择的数据
  const cascaderDataArray = [
    {
      text: '省市1',
      child: ['XXXXX大学1', 'XXXXX大学2', 'XXXXX大学3', 'XXXXX大学4', 'XXXXX大学5', 'XXXXX大学6'
        , 'XXXXX大学7', 'XXXXX大学8', 'XXXXX大学9', 'XXXXX大学10', 'XXXXX大学11', 'XXXXX大学12']
    },
    {
      text: '省市2',
      child: ['XXXXX大学13', 'XXXXX大学14', 'XXXXX大学15', 'XXXXX大学16', 'XXXXX大学17', 'XXXXX大学18'
        , 'XXXXX大学19', 'XXXXX大学20', 'XXXXX大学21', 'XXXXX大学22', 'XXXXX大学23', 'XXXXX大学24']
    },
    {
      text: '省市3',
      child: ['XXXXX大学25', 'XXXXX大学26', 'XXXXX大学27', 'XXXXX大学28', 'XXXXX大学29', 'XXXXX大学30'
        , 'XXXXX大学31', 'XXXXX大学32', 'XXXXX大学33', 'XXXXX大学34', 'XXXXX大学35', 'XXXXX大学36']
    },
    {
      text: '省市4',
      child: ['XXXXX大学37', 'XXXXX大学38', 'XXXXX大学39', 'XXXXX大学40', 'XXXXX大学41', 'XXXXX大学42'
        , 'XXXXX大学43', 'XXXXX大学44', 'XXXXX大学45', 'XXXXX大学46', 'XXXXX大学47', 'XXXXX大学48']
    },
    {
      text: '省市5',
      child: ['XXXXX大学49', 'XXXXX大学50', 'XXXXX大学51', 'XXXXX大学52', 'XXXXX大学53', 'XXXXX大学54'
        , 'XXXXX大学55', 'XXXXX大学56', 'XXXXX大学57', 'XXXXX大学58', 'XXXXX大学59', 'XXXXX大学60']
    },
    {
      text: '省市6',
      child: ['XXXXX大学61', 'XXXXX大学62', 'XXXXX大学63', 'XXXXX大学64', 'XXXXX大学65', 'XXXXX大学66'
        , 'XXXXX大学67', 'XXXXX大学68', 'XXXXX大学69', 'XXXXX大学70', 'XXXXX大学71', 'XXXXX大学72',
        'XXXXX大学73', 'XXXXX大学74', 'XXXXX大学75', 'XXXXX大学76', 'XXXXX大学77', 'XXXXX大学78', 'XXXXX大学79',
         'XXXXX大学80', 'XXXXX大学81', 'XXXXX大学82', 'XXXXX大学83', 'XXXXX大学84', 'XXXXX大学85', 'XXXXX大学86']
    }
  ]
  // 获取级联选择相关dom元素，方便操作
  let signUpArea = document.getElementById("signUpArea") // 地区表单项
  let signUpAreaInput = document.getElementById("signUpAreaInput")  // 地区选择框
  let cascader = null
  signUpArea.onclick = (event) => {
    if (cascader == null || cascader == undefined) { // 选择框不存在则创建
      cascader = addCascader(cascaderDataArray)
    }
    if (cascader.style.display != "none" && cascader.style.display != "") { // 创建后通过disply控制显示消失
      cascader.style.display = "none"
      signUpAreaInput.className = "sign-up-input"

    } else {
      cascader.style.display = "block"
      signUpAreaInput.className = "sign-up-input-focus"

    }
  }


  // 获取选择框相关dom元素
  const signUpYear = document.querySelector("#signUpYear"); // 年份div
  const signUpYearInput = document.getElementById("signUpYearInput"); // 年份选择框
  let selectDataArray = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021] // 年份选项
  let select = null // 存放选择框dom元素
  signUpYear.onclick = (event) => {
    if (select == null || select == undefined) { // 选择框不存在则创建
      select = addSelect(selectDataArray)
    }
    if (select.style.display != "none" && select.style.display != "") { // 创建后通过disply控制显示消失
      select.style.display = "none"
      signUpYearInput.className = "sign-up-input"

    } else {
      select.style.display = "block"
      signUpYearInput.className = "sign-up-input-focus"

    }
  }

  // 为dom添加事件监听，当点击级联选择和选择框以外的区域时，两框隐藏
  document.addEventListener("click", (event) => { // 用于点击选择框外关闭选择框的监听器
    if (select != null && event.target != signUpYearInput) {
      select.style.display = "none"
      signUpYearInput.className = "sign-up-input"
    }
    if (cascader != null && event.target != signUpAreaInput) {
      cascader.style.display = "none"
      signUpAreaInput.className = "sign-up-input"
    }
  })



  // 课程安排tabs切换
  let courseArrangementData = [ //课程安排数据
    {
      image: './images/courseArrangement.jpg',
      title: '第一课 这里是课程名称',
      content: '这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要。',
      tags: ['HTML']
    }, {
      image: './images/courseArrangement.jpg',
      title: '第二课 这里是课程名称',
      content: '这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要。',
      tags: ['CSS']
    }, {
      image: './images/courseArrangement.jpg',
      title: '第三课 这里是课程名称',
      content: '这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要。',
      tags: ['JavaScript']
    }, {
      image: './images/courseArrangement.jpg',
      title: '第四课 这里是课程名称',
      content: '这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要。',
      tags: ['HTML', 'CSS', 'JavaScript']
    }, {
      image: './images/courseArrangement.jpg',
      title: '第五课 这里是课程名称',
      content: '这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要。',
      tags: ['HTML', 'CSS', 'JavaScript']
    }, {
      image: './images/courseArrangement.jpg',
      title: '第六课 这里是课程名称',
      content: '这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要，这里是课程内容的概要。',
      tags: ['HTML', 'CSS', 'JavaScript']
    }
  ]
  // 获取tab切换需要的dom元素
  let tabs = document.querySelectorAll(".tab") //获取所有的tab
  let courseContent = document.querySelector("#courseContent") // 获取需要显示的内容框
  for (let i = 0; i < tabs.length; i++) {
    tabs[i].onclick = (event) => {
      resetTabs(tabs)
      tabs[i].className = "tab tab-active"
      courseContent.innerHTML = createcourseContentHTML(courseArrangementData, tabs[i].title)
    }
  }


  // 报名，进行表单验证
  // 获取相关dom元素
  let signUpFrom = document.getElementById("signUpFrom") // 获取报名的表单盒子
  let signUpEmail = document.getElementById("signUpEmail") // 获取邮箱输入框
  let signUpBtn = document.getElementById("signUpBtn") // 获取报名按钮
  let formContent = document.getElementById("formContent") // 获取表单内容框
  let formSuuccess = document.getElementById("formSuuccess") // 获取成功后的显示框
  let tip = null // 定义tip元素
  let timer = null // 定时器计时
  signUpBtn.onclick = (event) => {
    // 获取各项输入内容的值
    let signUpYearVal = signUpYearInput.value
    let signUpAreaVal = signUpAreaInput.value
    let signUpEmailVal = signUpEmail.value
    let isSuccess = null
    let text = null
    if (signUpAreaVal == "") { //判断学校是否为空
      isSuccess = false
      text = "您的学校不可以为空，请选择您的学校"
    } else if (signUpYearVal == "") {  // 判断入学年份是否为空
      isSuccess = false
      text = "您的入学年份不可以为空，请选择您的入学年份"
    } else if (!/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(signUpEmailVal)) { // 判断邮箱是否正确
      isSuccess = false
      text = "邮箱地址不符合要求（" + signUpEmailVal + "），请重新输入"
    } else { // 全部正确，报名成功
      isSuccess = true
      text = "恭喜您,来自 " + signUpAreaVal + " " + signUpYearVal + "级 " + signUpEmailVal + "同学,您的报名信息已记录,请关注您的邮件"

    }
    if (tip == null || tip == undefined) { // 提示框不存在则创建
      tip = createTipDialog(isSuccess, text)
      signUpFrom.appendChild(tip)
    }
    
    clearTimeout(timer)
    console.log(123);
    if (isSuccess) { // 提示框已经存在执行的方法
      tip.className = "tip success-tip"
      tip.innerText = text
      formContent.style.display = "none"
      formSuuccess.style.display = "block"
      timer = setTimeout(() => {
        tip.style.display = "none"
      }, 5000)
    } else {
      tip.className = "tip danger-tip"
      tip.innerText = text
      timer = setTimeout(() => {
        tip.style.display = "none"
      }, 3000)
    }
    tip.style.display = "block"
    event.stopPropagation() // 阻止事件冒泡
  }
  // 重现报名按钮的点击事件
  let formBack = document.getElementById("formBack")
  formBack.onclick = (event) => { // 回到报名页且输入框内容清空
    formContent.style.display = "flex"
    formSuuccess.style.display = "none"
    event.stopPropagation()
  }
}